package cn.anzhiyublog.staranimegallery.controller;

import cn.anzhiyublog.staranimegallery.annotation.Auth;
import cn.anzhiyublog.staranimegallery.model.domain.User;
import cn.anzhiyublog.staranimegallery.model.dto.user.*;
import cn.anzhiyublog.staranimegallery.model.enums.Authority;
import cn.anzhiyublog.staranimegallery.model.enums.StatusCode;
import cn.anzhiyublog.staranimegallery.model.response.Response;
import cn.anzhiyublog.staranimegallery.model.vo.UserVO;
import cn.anzhiyublog.staranimegallery.service.UserService;
import cn.anzhiyublog.staranimegallery.service.impl.SettingServiceImpl;
import cn.anzhiyublog.staranimegallery.util.ResultUtils;
import cn.anzhiyublog.staranimegallery.util.ThrowUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制层
 *
 * @author 安知一只鱼
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SettingServiceImpl settingService;

    /**
     * 注册
     *
     * @param registerRequest 注册请求
     * @param httpServletRequest HTTP请求头信息
     * @return 注册用户id
     */
    @PostMapping("/register")
    public Response<Long> register(@RequestBody RegisterRequest registerRequest,
                                   HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(registerRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        long registerId = userService.register(registerRequest);
        // 注册成功后自动登录
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setAccount(registerRequest.getAccount());
        loginRequest.setPassword(registerRequest.getPassword());
        // 注册后自动登录
        this.login(loginRequest, httpServletRequest);
        return ResultUtils.success(registerId);
    }

    /**
     * 登录
     *
     * @param loginRequest 登录请求
     * @param httpServletRequest 请求头信息
     * @return 登录用户信息
     */
    @PostMapping("/login")
    public Response<UserVO> login(@RequestBody LoginRequest loginRequest,
                                  HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(loginRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        User loginUser = userService.login(loginRequest, httpServletRequest);
        // 数据脱敏
        UserVO userVO = userService.ObjToVO(loginUser);
        return ResultUtils.success(userVO);
    }

    /**
     * 获取当前登录用户
     *
     * @param request HTTP请求头信息
     * @return 当前登录用户信息
     */
    @Auth(value = {Authority.GENERAL, Authority.MANAGE})
    @GetMapping("/get/login-user")
    public Response<UserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 数据脱敏
        UserVO userVO = userService.ObjToVO(loginUser);
        return ResultUtils.success(userVO);
    }

    /**
     * 退出登录
     *
     * @param request HTTP请求头信息
     * @return 退出登录成功
     */
    @Auth(value = {Authority.GENERAL, Authority.MANAGE})
    @GetMapping("/logout")
    public Response<?> logout(HttpServletRequest request) {
        userService.logout(request);
        return ResultUtils.success("退出登录成功");
    }

    /**
     * 添加用户（管理员）
     *
     * @param userAddRequest 用户添加请求
     * @return 添加用户id
     */
    @Auth(value = Authority.MANAGE)
    @PostMapping("/add")
    public Response<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userAddRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        return ResultUtils.success(userService.addUser(userAddRequest, userService.getLoginUser(request)));
    }

    /**
     * 删除用户（管理员）
     *
     * @param userDeleteRequest 用户删除请求
     * @return 删除成功
     */
    @Auth(value = Authority.MANAGE)
    @PostMapping("/delete")
    public Response<?> deleteUser(@RequestBody UserDeleteRequest userDeleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userDeleteRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        userService.deleteUser(userDeleteRequest, userService.getLoginUser(request));
        return ResultUtils.success("删除成功");
    }

    /**
     * 修改用户信息（管理员）
     *
     * @param userUpdateRequest 修改用户请求
     * @return 修改成功
     */
    @Auth(value = Authority.MANAGE)
    @PostMapping("/update")
    public Response<?> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userUpdateRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        userService.updateUser(userUpdateRequest,userService.getLoginUser(request));
        return ResultUtils.success("修改成功");
    }

    /**
     * 编辑用户信息（用户自己）
     *
     * @param userEditRequest 编辑用户请求
     * @param httpServletRequest HTTP请求头信息
     * @return 编辑成功
     */
    @PostMapping("/edit")
    public Response<?> editUser(@RequestBody UserEditRequest userEditRequest,
                                      HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(userEditRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        userService.editUser(userEditRequest, userService.getLoginUser(httpServletRequest));
        return ResultUtils.success("编辑成功");
    }

    /**
     * 修改用户密码（用户自己）
     *
     * @param userEditPasswordRequest 修改密码请求
     * @param httpServletRequest HTTP请求头信息
     * @return 修改成功
     */
    @Auth(value = {Authority.GENERAL, Authority.MANAGE})
    @PostMapping("/edit-password")
    public Response<?> editPassword(@RequestBody UserEditPasswordRequest userEditPasswordRequest,
                                          HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(userEditPasswordRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        userService.editPassword(userEditPasswordRequest, httpServletRequest);
        return ResultUtils.success("修改成功");
    }

    /**
     * 根据 id 获取用户
     *
     * @param userID 用户id
     * @return 用户信息
     */
    @GetMapping("/get")
    @Auth(value = {Authority.GENERAL, Authority.MANAGE})
    public Response<UserVO> getUserById(@RequestParam("id") long userID) {
        User user = userService.getUserById(userID);
        // 数据脱敏
        UserVO userVO = userService.ObjToVO(user);
        return ResultUtils.success(userVO);
    }

    /**
     * 分页查询用户 (仅管理员)
     *
     * @param userPageQueryRequest 分页查询请求
     * @return 分页用户信息
     */
    @Auth(value = Authority.MANAGE)
    @PostMapping("/list/page")
    public Response<Page<UserVO>> listUserByPage(@RequestBody UserPageQueryRequest userPageQueryRequest) {
        ThrowUtils.throwIf(userPageQueryRequest==null, StatusCode.BAD_REQUEST, "请求参数不能为空");
        Page<User> userPage = userService.listUserByPage(userPageQueryRequest);
        Page<UserVO> userVOPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        userVOPage.setRecords(userService.ObjToVO(userPage.getRecords()));
        return ResultUtils.success(userVOPage);
    }

    /**
     * 设置头像
     *
     * @param userId 用户id
     * @param pictureId 图片id
     * @param httpServletRequest HTTP请求头信息
     * @return 设置成功
     */
    @Auth(value = {Authority.GENERAL, Authority.MANAGE})
    @PostMapping("/set-avatar")
    public Response<?> setAvatar(@RequestParam("userId") long userId,
                                       @RequestParam("pictureId") long pictureId,
                                       HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(userId <= 0 || pictureId <= 0, StatusCode.BAD_REQUEST, "请求参数错误");
        userService.setAvatar(userId, pictureId, userService.getLoginUser(httpServletRequest));
        return ResultUtils.success("设置成功");
    }
}
